package com.china08.yxyapi.api.manage.tec.teaching.lesson.cloud;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.lessons.cloud.YxyLessonsCloudLesson;
import com.china08.yxyapi.entity.db.lessons.cloud.YxyLessonsCloudLessonItem;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.lesson.YxyLessonsCloudLessonItemRepository;
import com.china08.yxyapi.repository.db.lesson.YxyLessonsCloudLessonRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class TecCloudLessonFaBuController extends YxyApiBaseController {

    @Autowired
    YxyLessonsCloudLessonRepository lessonRepository;

    @Autowired
    YxyLessonsCloudLessonItemRepository itemRepository;

    @ApiOperation("")
    @RequestMapping(value = "/api_yw/manage/tec/teaching/lesson/cloud/fabu", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        String lessonId = reqModel.lessonId;

        // 判断当前课程里面是否有草稿数据
        List<YxyLessonsCloudLessonItem> items = itemRepository.findByLessonIdAndStatus(lessonId, 0);
        Assert.isTrue(items.size() > 0, "当前课程没有要发布的课时");
        /**
         * 发布课程，修改课程为待审核， 将所有草稿课时修改为待审核
         */
        YxyLessonsCloudLesson lesson = lessonRepository.findById(lessonId);
        Assert.isTrue(lesson != null, "未获取到课程");

        Integer status = lesson.getStatus();
        // 审核未通过，课程状态未待审核
        if (status != 2) {
            // 修改课程未待审核
            lesson.setStatus(1);
        }

        lesson.setUpdateDate(new Date());
        lesson.setCreateDate(new Date());
        lessonRepository.save(lesson);

        // 获取所有草稿课程
        for (YxyLessonsCloudLessonItem item : items) {
            item.setStatus(1);
        }
        itemRepository.save(items);
    }

    public static class ReqModel extends YxyApiReqModel {
        public String lessonId;
    }
}
